package com.jlnk.androidfmc.database;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteBlobTooBigException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Base64;
import android.util.Log;


import com.jlnk.androidfmc.entity.Post;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class PostDatabase extends SQLiteOpenHelper {
    private static final int PAGE_SIZE = 1;
    private static PostDatabase instance;
    private static final String DATABASE_NAME = "farmer.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "posts";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_CONTENT = "content";
    private static final String COLUMN_IMAGE_URL = "image_url";
    private PostDatabase db;
    private static final String CREATE_TABLE = "CREATE TABLE "
            + TABLE_NAME + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COLUMN_CONTENT + " TEXT,"
            + COLUMN_IMAGE_URL + " TEXT" + ")";


    public PostDatabase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public static synchronized PostDatabase getInstance(Context context) {
        if (instance == null) {
            instance = new PostDatabase(context);
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    protected List<Post> doInBackground(Void... params) {
        // 获取第一页的数据
        try {
            List<Post> posts = db.getAllPosts(1, PAGE_SIZE);
            if (posts == null) {
                return Collections.emptyList();
            }
            return posts;
        } catch (SQLiteBlobTooBigException e) {
            Log.e("LoadPostsTask", "Error loading posts", e);
            return Collections.emptyList();
        }
    }


    // 插入帖子的方法
    public long insertPost(String content, byte[] imageByteArray) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_CONTENT, content);
        // 将字节数组转换为字符串存储，这里使用 Base64 编码
        values.put(COLUMN_IMAGE_URL, Base64.encodeToString(imageByteArray, Base64.DEFAULT));
        return db.insert(TABLE_NAME, null, values);
    }


    // 添加一个新方法来获取特定帖子的图片数据
    public byte[] getPostImage(long postId) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, new String[]{COLUMN_IMAGE_URL}, COLUMN_ID + "=?",
                new String[]{String.valueOf(postId)}, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            String encodedImage = cursor.getString(0);
            cursor.close();
            // 将Base64编码的字符串转换回字节数组
            return Base64.decode(encodedImage, Base64.DEFAULT);
        }
        return null;
    }

    // 查询所有帖子的方法
    @SuppressLint("Range")
    public List<Post> getAllPosts(int page, int pageSize) {
        List<Post> postList = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT " + COLUMN_ID + ", " + COLUMN_CONTENT + " FROM " + TABLE_NAME, null);

        if (cursor.moveToFirst()) {
            do {
                Post post = new Post();
                post.setId(cursor.getInt(cursor.getColumnIndex(COLUMN_ID)));
                post.setContent(cursor.getString(cursor.getColumnIndex(COLUMN_CONTENT)));
                // 注意：这里我们不查询图片数据，以避免SQLiteBlobTooBigException异常
                postList.add(post);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return postList;
    }

    // 更新帖子的方法
    public int updatePost(long id, String content) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_CONTENT, content);
        return db.update(TABLE_NAME, values, COLUMN_ID + " = ?", new String[]{String.valueOf(id)});
    }

    // 删除帖子的方法
    public void deletePost(long id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME, COLUMN_ID + " = ?", new String[]{String.valueOf(id)});
    }





}
